import { defineStore } from 'pinia'
import { api, users } from '@/services/api'
import type { ReimbursementApplication, User, UserRole } from '@/services/models'

interface AppState {
  applications: ReimbursementApplication[]
  users: User[]
  currentUser: User
  loading: boolean
  error: string | null
  userStats: {
    total: number
    pending: number
    completed: number
    rejected: number
  } | null
}

export const useApplicationStore = defineStore('application', {
  state: (): AppState => ({
    applications: [],
    users: users,
    currentUser: users[0], // 默认是第一个员工
    loading: false,
    error: null,
    userStats: null,
  }),

  getters: {
    // 计算当前用户的待办任务
    pendingTasksForCurrentUser(state): ReimbursementApplication[] {
      const { role } = state.currentUser
      return state.applications.filter((app) => {
        if (role === 'head' && app.status === 'PENDING_HEAD_REVIEW') return true
        if (role === 'finance' && app.status === 'PENDING_FINANCE_REVIEW') return true
        if (role === 'gm' && app.status === 'PENDING_GM_REVIEW') return true
        return false
      })
    },
    // 计算我提交的申请
    mySubmissions(state): ReimbursementApplication[] {
      return state.applications.filter((app) => app.applicantId === state.currentUser.id)
    },
    // 获取被驳回的申请（可重新提交）
    rejectedApplications(state): ReimbursementApplication[] {
      return state.applications.filter(
        (app) => app.applicantId === state.currentUser.id && app.status === 'REJECTED',
      )
    },
    // 获取可撤销的申请（只有申请人可以撤销自己的待审批申请）
    cancellableApplications(state): ReimbursementApplication[] {
      return state.applications.filter(
        (app) =>
          app.applicantId === state.currentUser.id &&
          ['PENDING_HEAD_REVIEW', 'PENDING_FINANCE_REVIEW', 'PENDING_GM_REVIEW'].includes(
            app.status,
          ),
      )
    },
    // 获取所有待审批的申请（管理员视图）
    allPendingApplications(state): ReimbursementApplication[] {
      return state.applications.filter((app) =>
        ['PENDING_HEAD_REVIEW', 'PENDING_FINANCE_REVIEW', 'PENDING_GM_REVIEW'].includes(app.status),
      )
    },
  },

  actions: {
    // 切换用户
    async switchUser(userId: string) {
      const user = this.users.find((u) => u.id === userId)
      if (user) {
        this.currentUser = user
        // 切换用户后重新加载数据和统计
        await this.fetchApplications()
        await this.fetchUserStats()
      }
    },

    // 获取所有申请
    async fetchApplications() {
      this.loading = true
      this.error = null
      try {
        this.applications = await api.getApplications()
      } catch (e: any) {
        this.error = e.message
      } finally {
        this.loading = false
      }
    },

    // 获取用户统计
    async fetchUserStats() {
      try {
        this.userStats = await api.getUserStats(this.currentUser.id)
      } catch (e: any) {
        console.error('获取用户统计失败:', e.message)
      }
    },

    // 提交新申请
    async submitApplication(
      application: Omit<ReimbursementApplication, 'id' | 'createdAt' | 'updatedAt'>,
    ) {
      this.loading = true
      this.error = null
      try {
        const newApplication = await api.submitApplication(application)
        // 添加到本地状态
        this.applications.push(newApplication)
        // 更新用户统计
        await this.fetchUserStats()
        return newApplication
      } catch (e: any) {
        this.error = e.message
        throw e
      } finally {
        this.loading = false
      }
    },

    // 审批通过
    async approve(applicationId: string, comment: string) {
      this.loading = true
      this.error = null
      const app = this.applications.find((a) => a.id === applicationId)
      if (!app) {
        this.error = '申请不存在'
        return
      }

      // 核心流转逻辑
      let nextStatus: ReimbursementApplication['status'] = app.status
      if (app.status === 'PENDING_HEAD_REVIEW') nextStatus = 'PENDING_FINANCE_REVIEW'
      else if (app.status === 'PENDING_FINANCE_REVIEW') nextStatus = 'PENDING_GM_REVIEW'
      else if (app.status === 'PENDING_GM_REVIEW') nextStatus = 'COMPLETED'

      try {
        const updatedApp = await api.updateApplication(applicationId, nextStatus, {
          approverId: this.currentUser.id,
          approverName: this.currentUser.name,
          action: 'approve',
          comment,
        })

        // 更新本地状态
        const index = this.applications.findIndex((a) => a.id === applicationId)
        if (index !== -1) {
          this.applications[index] = updatedApp
        }

        // 如果是当前用户的申请，更新统计
        if (app.applicantId === this.currentUser.id) {
          await this.fetchUserStats()
        }
      } catch (e: any) {
        this.error = e.message
        throw e
      } finally {
        this.loading = false
      }
    },

    // 审批驳回
    async reject(applicationId: string, comment: string) {
      this.loading = true
      this.error = null
      try {
        const updatedApp = await api.updateApplication(applicationId, 'REJECTED', {
          approverId: this.currentUser.id,
          approverName: this.currentUser.name,
          action: 'reject',
          comment,
        })

        // 更新本地状态
        const index = this.applications.findIndex((a) => a.id === applicationId)
        if (index !== -1) {
          this.applications[index] = updatedApp
        }

        // 如果是当前用户的申请，更新统计
        if (updatedApp.applicantId === this.currentUser.id) {
          await this.fetchUserStats()
        }
      } catch (e: any) {
        this.error = e.message
        throw e
      } finally {
        this.loading = false
      }
    },

    // 重新提交被驳回的申请
    async resubmitApplication(id: string) {
      try {
        const application = await api.resubmitApplication(id)
        // 更新本地状态
        const index = this.applications.findIndex((app) => app.id === id)
        if (index !== -1) {
          this.applications[index] = application
        }
        return application
      } catch (error) {
        console.error('Failed to resubmit application:', error)
        throw error
      }
    },

    // 更新申请数据（编辑后重新提交）
    async updateApplicationData(
      id: string,
      updatedData: {
        applicantName: string
        amount: number
        description: string
        expenseType: string
        invoiceInfo?: string
      },
    ) {
      try {
        const application = await api.updateApplicationData(id, updatedData)
        // 更新本地状态
        const index = this.applications.findIndex((app) => app.id === id)
        if (index !== -1) {
          this.applications[index] = application
        }
        return application
      } catch (error) {
        console.error('Failed to update application data:', error)
        throw error
      }
    },

    // 撤销申请
    async cancelApplication(applicationId: string, comment: string) {
      this.loading = true
      this.error = null

      const app = this.applications.find((a) => a.id === applicationId)
      if (!app) {
        this.error = '申请不存在'
        return
      }

      // 检查权限：只有申请人可以撤销自己的申请
      if (app.applicantId !== this.currentUser.id) {
        this.error = '只有申请人可以撤销自己的申请'
        return
      }

      try {
        const updatedApp = await api.cancelApplication(applicationId, comment)

        // 更新本地状态
        const index = this.applications.findIndex((a) => a.id === applicationId)
        if (index !== -1) {
          this.applications[index] = updatedApp
        }

        // 更新用户统计
        await this.fetchUserStats()
      } catch (e: any) {
        this.error = e.message
        throw e
      } finally {
        this.loading = false
      }
    },

    // 清除错误信息
    clearError() {
      this.error = null
    },
  },
})
